﻿using Avalon.Core.MVC.Attributes;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Avalon.Core.MVC.Helpers
{
    public class EditFormHelper : Avalon.Core.MVC.IViewRenderHelper
    {
        public MvcHtmlString Render(HtmlHelper htmlHelper)
        {
            string controllerName = htmlHelper.ViewContext.RouteData.Values["controller"].ToString();
            string actionName = htmlHelper.ViewContext.RouteData.Values["action"].ToString();

            StringBuilder builder = new StringBuilder();

            builder.AppendFormat(@"<form method='post' action='/{0}/{1}'>", controllerName, actionName);

            ///Get an instace of the meta data provider
            ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => htmlHelper.ViewData.Model, htmlHelper.ViewData.Model.GetType());
            if (modelMetadata.Model == null) modelMetadata.Model = htmlHelper.ViewContext.ViewData.Model;

            // When this form is used to create a referenced type set the parent information
            ModelMetadata parentMetadata = modelMetadata.GetParentProperty();
            if (parentMetadata != null) {
                string parentId = parentMetadata.GetParentId();
                builder.AppendFormat(@"<input type='hidden' name='parentId' value='{0}' />", parentId);
                builder.AppendFormat(@"<input type='hidden' name='parentName' value='{0}' />", parentMetadata.ModelType.Name);
            }

            builder.AppendFormat(@"<fieldset><legend>{0}</legend>", modelMetadata.GetTitle());

            foreach (var propertyMetadata in modelMetadata.Properties.Where(p => p.IsSimpleProperty()).OrderBy(p => p.Order))
            {
                if (propertyMetadata.AdditionalValues.ContainsKey(IgnoreAttribute.Key)) continue;
                else builder.Append(ControlBuilder.CreateInputControl(htmlHelper, propertyMetadata));
            }
            
            builder.AppendFormat(@"<input type='submit' class='btn' value='Save' />");
            var id = htmlHelper.ViewData.Model.GetType().GetProperty("Id").GetValue(htmlHelper.ViewData.Model);
            builder.AppendFormat(@"<a href='/{0}/{1}/{2}' class='btn'>Cancel</a>", controllerName, "Detail", id != null ? id.ToString() : string.Empty);
            builder.AppendFormat(@"</fieldset>");
            builder.AppendFormat(@"</form>");

            return new MvcHtmlString(builder.ToString());
        }
    }
}
